//将上传后文件的size转化为人类可读文件大小字符串
export function formatFileSize(bytes, decimals = 2) {
  if (bytes === 0) return '0 Bytes'

  const k = 1024
  const dm = decimals < 0 ? 0 : decimals
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']

  const i = Math.floor(Math.log(bytes) / Math.log(k))

  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
}

function formatTimestamp() {
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')

  return `${month}-${day}-${hour}-${minute}`
}

export function dealFileName(fileName, typeStr) {
  const [name, type] = fileName.split('.')
  return `${name}-${typeStr}${formatTimestamp()}.${type}`
}
export function formatNumber(num, digits) {
  let numStr = num.toString()
  while (numStr.length < digits) {
    numStr = '0' + numStr
  }
  return numStr
}
// 使用a标签下载文件
export const downloadFile = (file) => {
  if (!file || !file.fileUrl) return

  // 创建一个临时链接用于下载
  const link = document.createElement('a')
  link.href = file.fileUrl
  link.download = file.fileName || 'download'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
